package com.gxd.service.impl;

import com.gxd.dao.AddressDao;
import com.gxd.dao.impl.AddressDaoImpl;
import com.gxd.domain.Address;
import com.gxd.domain.Order;
import com.gxd.service.AddressService;
import com.gxd.service.OrderService;
import com.gxd.util.DBUtils;

import java.sql.SQLException;
import java.util.List;

public class AddressServiceImpl implements AddressService {
    AddressDao addressDao = new AddressDaoImpl();
    @Override
    public List<Address> findByUid(int id) {

        return addressDao.findByUid(id);
    }

    @Override
    public void addAddress(Address address) {
        addressDao.addAddress(address);
    }

    @Override
    public void deleteById(int id) {
        OrderService orderService = new OrderServiceImpl();
        Order order=orderService.selectByAid(id);
        if(order==null){
            addressDao.deleteById(id);
        }else {
            throw new RuntimeException("与订单关联，无法删除");
        }

    }

    @Override
    public void updateAddress(Address address) {
        addressDao.updateAddress(address);
    }

    @Override
    public void setDefaultAddress(String aid, int uid) {
        try {
            DBUtils.begin();
            addressDao.clearDefaultAddress(uid);

            addressDao.setDefaultAddress(aid);
            DBUtils.commit();
        } catch (Exception e) {
            try {
                DBUtils.rollback();

            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                DBUtils.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
